package com.lcxw.hxzbapi.controller.membercontroller;

import com.alibaba.fastjson.JSONObject;
import com.lcxw.hxzbapi.entity.pojo.Photo;
import com.lcxw.hxzbapi.entity.pojo.RichLevel;
import com.lcxw.hxzbapi.entity.requestBean.AddCoinReq;
import com.lcxw.hxzbapi.entity.requestBean.QueryOneInfoReq;
import com.lcxw.hxzbapi.service.AttentionService;
import com.lcxw.hxzbapi.tencentim.common.TencentImRealization;
import com.lcxw.hxzbcommon.entity.ErrorCode;

import java.util.*;
import javax.annotation.Resource;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.lcxw.hxzbapi.controller.appcontroller.LoginController;
import com.lcxw.hxzbapi.entity.pojo.YwpdMember;
import com.lcxw.hxzbapi.entity.requestBean.RequestParamBasic;
import com.lcxw.hxzbapi.entity.response.Response;
import com.lcxw.hxzbapi.service.YwpdMemberService;
import com.lcxw.hxzbcommon.common.StringUtil;

/**
 *
 */
@RestController
@CrossOrigin
@RequestMapping("api/user")
public class MemberController {

    private Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Resource
    TencentImRealization tencentImRealization;

    @Resource
    YwpdMemberService ywpdMemberService;

    @Resource
    MemberRealization memberRealization;

    @Resource
    AttentionService attentionService;

    /**
     * 1、获取用户所有信息接口
     *
     * @param requestParam
     * @return
     */
    @PostMapping("/info/get")
    public Response memberInfoQuery(@Valid @RequestBody RequestParamBasic requestParam) {
        //构造响应
        Response response = new Response();

        Map<String, Object> data = new LinkedHashMap<>();
        long userId = Long.parseLong(requestParam.getUserId());

        try {
            data = memberRealization.getUserInfo(userId);
        } catch (Exception e) {
            return Response.dbFail(logger, "get user info");
        }

        response.setCode(0);
        response.setDesc("success");
        response.setData(data);

        return response;
    }

    @PostMapping("/info/set")
    public Response userInfoSet(@RequestBody JSONObject requestParams) {
        logger.info("{} set user info : {}", requestParams.getString("userId"), requestParams);
        Response response = new Response();

        long userId = Long.parseLong(requestParams.getString("userId"));
        YwpdMember ywpdMember;
        try {
            ywpdMember = ywpdMemberService.selectYwpdMemberByUserId(userId);

            JSONObject imBody = new JSONObject();
            imBody.put("From_Account", userId + "");
            List<JSONObject> profileItem = new ArrayList<>();

            if (null != requestParams.getString("nickName")) {
                ywpdMember.setNickName(requestParams.getString("nickName"));
                JSONObject profile = new JSONObject();
                profile.put("Tag", "Tag_Profile_IM_Nick");
                profile.put("value", requestParams.getString("nickName"));
                profileItem.add(profile);
            }
            if (null != requestParams.getString("signature")) {
                ywpdMember.setSignature(requestParams.getString("signature"));
                JSONObject profile = new JSONObject();
                profile.put("Tag", "Tag_Profile_IM_SelfSignature");
                profile.put("value", requestParams.getString("signature"));
                profileItem.add(profile);
            }
            if (null != requestParams.getString("sex")) {
                ywpdMember.setSex(requestParams.getString("sex"));
                String sex;
                if (requestParams.getString("sex").equals("男")) {
                    sex = "Gender_Type_Male";
                } else if (requestParams.getString("sex").equals("女")) {
                    sex = "Gender_Type_Female";
                } else {
                    sex = "Gender_Type_Unknown";
                }
                JSONObject profile = new JSONObject();
                profile.put("Tag", "Tag_Profile_IM_Gender");
                profile.put("value", sex);
                profileItem.add(profile);
            }
            if (null != requestParams.getString("imgUrl")) {
                ywpdMember.setImgUrl(requestParams.getString("imgUrl"));
                JSONObject profile = new JSONObject();
                profile.put("Tag", "Tag_Profile_IM_Image");
                profile.put("value", requestParams.getString("imgUrl"));
                profileItem.add(profile);
            }
            if (null != requestParams.getString("age")) {
                ywpdMember.setAge(Integer.parseInt(requestParams.getString("age")));
            }
            if (null != requestParams.getString("occupation")) {
                ywpdMember.setOccupation(requestParams.getString("occupation"));
            }
            if (null != requestParams.getString("birthday")) {
                ywpdMember.setBirthday(requestParams.getString("birthday"));
            }
            if (null != requestParams.getString("province")) {
                ywpdMember.setProvince(requestParams.getString("province"));
            }
            if (null != requestParams.getString("city")) {
                ywpdMember.setCity(requestParams.getString("city"));
            }
            if (null != requestParams.getString("school")) {
                ywpdMember.setSchool(requestParams.getString("school"));
            }

            //数据库中更新用户信息
            ywpdMemberService.updateYwpdMember(ywpdMember);

            //在腾讯的IM系统 中更新用户信息
            imBody.put("ProfileItem", profileItem);
            tencentImRealization.updateImUserInfo(imBody);

            response.setCode(0);
            response.setDesc("success");

        } catch (Exception e) {
            e.printStackTrace();
            logger.warn("用户查询失败，数据库操作失败。");
            response.setCode(ErrorCode.DB_OPERATE_FAIL);
            response.setDesc("查询数据库失败，请联系后台开发人员");
            return response;
        }

        return response;
    }

    @PostMapping("/password/forget")
    public Response forgetPassword(@RequestBody JSONObject requestParams) {
        logger.info("{} forget password,wanna reset.", requestParams.getString("telephone"));
        Response response = new Response();

        String telephone = requestParams.getString("telephone");
        String password = requestParams.getString("password");

        if (!StringUtil.checkPhoneNum(telephone) || StringUtil.isEmpty(password)) {
            response.setCode(ErrorCode.PARAM_ERROR);
            response.setDesc("telephoneNum or password is incorrect");
            return response;
        }

        YwpdMember ywpdMember;
        try {
            ywpdMember = ywpdMemberService.selectYwpdMemberByTelephone(telephone);
            if (null == ywpdMember) {

                logger.warn("The member with telephone {} is not exist 。", telephone);
                response.setCode(ErrorCode.INVALID_PARAM);
                response.setDesc("The member with telephone " + telephone + "is not exist 。");
                return response;

            }

            ywpdMember.setPassword(password);
            ywpdMemberService.updateYwpdMember(ywpdMember);
            response.setCode(0);
            response.setDesc("success");

        } catch (Exception e) {
            e.printStackTrace();
            logger.warn("数据库操作失败。");
            response.setCode(ErrorCode.DB_OPERATE_FAIL);
            response.setDesc("数据库操作失败，请联系后台开发人员");
            return response;
        }

        return response;
    }

    @PostMapping("/password/reset")
    public Response resetPassword(@Valid @RequestBody JSONObject requestParams) {
        logger.info("{} reset password", requestParams.getString("userId"));
        Response response = new Response();

        long userId = Long.parseLong(requestParams.getString("userId"));
        String telephone = requestParams.getString("telephone");
        String password = requestParams.getString("password");

        if (StringUtil.isEmpty(password)) {
            response.setCode(ErrorCode.PARAM_ERROR);
            response.setDesc("password format is incorrect");
            return response;
        }

        YwpdMember ywpdMember;
        try {
            ywpdMember = ywpdMemberService.selectYwpdMemberByUserId(userId);

            ywpdMember.setPassword(password);
            ywpdMember.setTelephone(telephone);
            ywpdMemberService.updateYwpdMember(ywpdMember);
            response.setCode(0);
            response.setDesc("success");

        } catch (Exception e) {
            e.printStackTrace();
            logger.warn("数据库操作失败。");
            response.setCode(ErrorCode.DB_OPERATE_FAIL);
            response.setDesc("数据库操作失败，请联系后台开发人员");
            return response;
        }

        return response;
    }

    /**
     * 更改用户虚拟货币值的接口
     */
    @PostMapping("/addCoin")
    public Response addCoin(@RequestBody AddCoinReq addCoinReq) {
        long userId = Long.parseLong(addCoinReq.getUserId());
        int addCoin = addCoinReq.getAddCoin();
        memberRealization.addCoin(addCoin, userId);
        return Response.ok();
    }

    /**
     * 查询用户的详细信息，用于个人中心展示，或者查看其它用户信息
     */
    @PostMapping("/info/queryOne")
    public Response queryOneInfo(@RequestBody QueryOneInfoReq queryOneInfoReq) {
        JSONObject data = new JSONObject();
        long userId = Long.parseLong(queryOneInfoReq.getUserId());
        long queriedUserId = Long.parseLong(queryOneInfoReq.getQueriedUserId());
        Map<String, Object> userInfo;

        //1、第一步，获取用户的基础信息
        try {
            userInfo = memberRealization.getFriendInfo(queriedUserId);
        } catch (Exception e) {
            return Response.dbFail(logger, "query user info");
        }

        //2、第二步，获取用户的粉丝数量
        int fansNum = memberRealization.getFansNum(queriedUserId);

        //3、第三步，userId 和 queriedUserId 两个用户的距离
        double distance = memberRealization.getDistance(userId, queriedUserId);

        //4、第四步，获取查询用户的财富等级
        int consumeTotal = memberRealization.getConsumeTotal(queriedUserId);
        RichLevel richLevel = null;
        try {
            richLevel = memberRealization.getRichLevel(consumeTotal);
        } catch (Exception e) {
            logger.error("查询用户的财富等级失败。");
        }

        //5、 第五步，获取相册信息
        List<Photo> photos = memberRealization.getAllPhotos(queriedUserId);


        //2020/10/20 当把头像中的某个照片设置为头像，展示相册的时候需要把这张照片放在第一个位置。
        String imgUrl= ywpdMemberService.selectImgUrlByuserId(userId);
        if(null!=imgUrl&&!photos.isEmpty()){
            int index=0;
            for(int i=0;i<photos.size();i++){
                if(imgUrl.equals(photos.get(i).getPhotoUrl())){
                    index=i;
                }
            }
            Collections.swap(photos, index, 0);
        }



        data.put("baseInfo", userInfo);
        data.put("fansNum", fansNum);
        data.put("distance", distance);
        data.put("richLevel", richLevel);
        data.put("photos", photos);

        return Response.ok(data);
    }

    //获取我的基础信息接口
    @PostMapping("/baseInfo/get")
    public Response getBaseInfo(@RequestBody RequestParamBasic requestbody) {
        long userId = Long.parseLong(requestbody.getUserId());
        Map<String, Object> userInfo;
        try {
            userInfo = memberRealization.getFriendInfo(userId);
        } catch (Exception e) {
            return Response.dbFail(logger, "查询用户信息失败");
        }
        int fansNum = attentionService.getFansNum(userId);
        int attNum = attentionService.getAttNum(userId);
        int friendNum = attentionService.getFriendNum(userId);

        userInfo.put("fansNum", fansNum);
        userInfo.put("attNum", attNum);
        userInfo.put("friendNum", friendNum);
        return Response.ok(userInfo);
    }

    //获取会员状态接口
    @PostMapping("/vipStatus/get")
    public Response getVipStatus(@RequestBody RequestParamBasic getVipStatus) {
        long userId = Long.parseLong(getVipStatus.getUserId());
        YwpdMember ywpdMember = ywpdMemberService.selectYwpdMemberByUserId(userId);
        JSONObject data = new JSONObject();
        data.put("vip", ywpdMember.getVip());
        String vipExpire = "";
        if (ywpdMember.getVip() == 1) {
            vipExpire = ywpdMember.getVipExpire().split(" ")[0];
        }

        data.put("vipExpire", vipExpire);

        return Response.ok(data);

    }
}
